package com.wk.code.wkserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wk.code.wkserver.constant.enums.AccountTypeEnum;
import com.wk.code.wkserver.entity.UserAccountRecord;
import com.wk.code.wkserver.mapper.UserAccountRecordMapper;
import com.wk.code.wkserver.response.admin.UserBalanceRecord;
import com.wk.code.wkserver.service.IUserAccountRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wk.code.wkserver.utils.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户账户记录表 服务实现类
 * </p>
 *
 * @author wq
 * @since 2021-08-15
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserAccountRecordServiceImpl extends ServiceImpl<UserAccountRecordMapper, UserAccountRecord> implements IUserAccountRecordService {

    @Override
    public void saveRecord(Integer techUserId, BigDecimal techAccount, Integer type, Integer accountType, BigDecimal balance, Integer withdrawId) {
        UserAccountRecord record = new UserAccountRecord();
        record.setAccountType(accountType);
        record.setUserId(techUserId);
        record.setAmount(techAccount);
        record.setType(type);
        record.setBalance(balance);
        record.setUserId(techUserId);
        record.setWithdrawId(withdrawId);
        save(record);
    }

    @Override
    public List<UserBalanceRecord> selectRecordList(Integer userId) {
        List<UserAccountRecord> accountRecords = baseMapper.selectList(new LambdaQueryWrapper<UserAccountRecord>().
                eq(UserAccountRecord::getUserId, userId).orderByDesc(UserAccountRecord::getCreateTime));
        if (!CollectionUtils.isEmpty(accountRecords)) {
            return accountRecords.stream().map(x -> {
                UserBalanceRecord record = new UserBalanceRecord();
                BeanUtils.copyProperties(x, record);
                record.setCreateTime(DateUtils.localDateTime2Date(x.getCreateTime()));
                record.setUpdateTime(DateUtils.localDateTime2Date(x.getUpdateTime()));
                return record;
            }).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public UserAccountRecord selectRecordByWithdrawId(Integer withdrawId) {
        return baseMapper.selectOne(new LambdaQueryWrapper<UserAccountRecord>().
                eq(UserAccountRecord::getWithdrawId, withdrawId).
                eq(UserAccountRecord::getAccountType, AccountTypeEnum.WITHDRAW.getCode()));
    }
}
